package com.jeefw.cloud.httpdoc;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

/**
 * Spring Boot 集成 Mybatis的基本入口
 */
@Configuration
@MapperScan(basePackages = "com.jeefw.**.daointerface")
@EnableConfigurationProperties(MybatisProperties.class)
public class MyBatisConfiguration {
	
	@Bean
	@Qualifier("patternResolver")
	public ResourcePatternResolver getResourceLoader() {
		return new PathMatchingResourcePatternResolver();
	}
	
	@Bean
	@ConfigurationProperties("spring.mybatis")
	public SqlSessionFactory sqlSessionFactory(MybatisProperties properties,
			@Qualifier("druidDataSource") DataSource ds, 
			@Qualifier("patternResolver") ResourcePatternResolver patternResolver) throws Exception {
		SqlSessionFactoryBean sfb = new SqlSessionFactoryBean();
		sfb.setDataSource(ds);
		sfb.setConfigLocation(patternResolver.getResource(properties.getConfigLocation()));
		sfb.setTypeHandlersPackage(properties.getTypeHandlersPackage());
		// 下边两句仅仅用于*.xml文件，如果整个持久层操作不需要使用到xml文件的话（只用注解就可以搞定），则不加
		sfb.setTypeAliasesPackage(properties.getTypeAliasesPackage());
		sfb.setMapperLocations(patternResolver.getResources(properties.getMapperLocations()));
		return sfb.getObject();
	}
}